package com.hugang.security;

/**
 * 线程死锁问题实例
 *
 * 1、死锁的理解：不同线程分别占用对方需要的同步资源不放弃，都在等待对方释放自己需要的同步资源，就形成了死锁。
 *
 * 2、说明：
 *      1）出现死锁后，不会出现异常，不会出现提示，只是所有的线程都处于阻塞状态，无法继续
 *      2）使用同步时，要避免出现死锁
 *
 * 问题排查：
 *  1、在当前目录的命令行下使用：jps -l
 *      24820 com.hugang.security.DeadLock
 *  2、使用 jstack 24820查看此进程的详细信息
 *  Found one Java-level deadlock:
 * =============================
 * "Thread-1":
 *   waiting to lock monitor 0x00000000036f80c8 (object 0x00000000d64388e0, a java.lang.StringBuffer),
 *   which is held by "Thread-0"
 * "Thread-0":
 *   waiting to lock monitor 0x000000001a789f78 (object 0x00000000d6438928, a java.lang.StringBuffer),
 *   which is held by "Thread-1"
 *
 * Java stack information for the threads listed above:
 * ===================================================
 * "Thread-1":
 *         at java.lang.StringBuffer.append(StringBuffer.java:271)
 *         - waiting to lock <0x00000000d64388e0> (a java.lang.StringBuffer)
 *         at com.hugang.security.DeadLock$2.run(DeadLock.java:47)
 *         - locked <0x00000000d6438928> (a java.lang.StringBuffer)
 *         at java.lang.Thread.run(Thread.java:745)
 * "Thread-0":
 *         at com.hugang.security.DeadLock$1.run(DeadLock.java:33)
 *         - waiting to lock <0x00000000d6438928> (a java.lang.StringBuffer)
 *         - locked <0x00000000d64388e0> (a java.lang.StringBuffer)
 *
 * Found 1 deadlock.
 *
 *
 * @author hg
 * @date 2020/6/15 18:25
 */
public class DeadLock {

    public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer();
        StringBuffer s2 = new StringBuffer();

        new Thread(){
            @Override
            public void run() {
                synchronized (s1){
                    s1.append("a");
                    s2.append("1");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (s2){
                        s1.append("b");
                        s2.append("2");

                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (s2){
                    s1.append("c");
                    s2.append("3");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (s1){
                        s1.append("d");
                        s2.append("4");

                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }).start();
    }
}

